package it.univpm.dii.tressette.ui;

import it.univpm.dii.tressette.R;
import android.util.DisplayMetrics;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class GameTableActivity extends Activity {
	private int[] myCards = { 101, 102, 103, 104, 105};
	public RelativeLayout myRelative;
	public Button myAdd;
	public Button myReset;
	public TextView myText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		myText=(TextView)this.findViewById(R.id.txt);
		myRelative = (RelativeLayout) this.findViewById(R.id.my_relative);
		myReset = (Button) this.findViewById(R.id.my_delete);
		myReset.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				myRelative.removeAllViews();
				refreshLayout();
			}
		});
		
		DisplayMetrics dm=new DisplayMetrics();
		int dimension = dm.widthPixels;
		
		for (int i = 0; i < myCards.length; i++) {
			Button btn = new Button(this.getApplicationContext());
			btn.setText(Integer.toString(myCards[i]));
			btn.setId(myCards[i]);
			btn.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					myRelative.removeView(arg0);
					refreshLayout();
				}

			});
			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
//			myText.append(Integer.toString(myRelative.getChildCount()));
//			myText.append("-"+Integer.toString(margin)+"|");
			//btn.setLayoutParams(lp);
			btn.setLayoutParams(lp);
			myRelative.addView(btn);
		}
		refreshLayout();
		
	}

	public void refreshLayout() {
		int nChild=myRelative.getChildCount();
		DisplayMetrics dm=new DisplayMetrics();
		int margin = 0; 
		if (nChild!=0) {
			margin = dm.widthPixels / myRelative.getChildCount();
		}
		for (int i = 0; i < myRelative.getChildCount(); i++) {
			myText.append(Integer.toString(myRelative.getChildCount()));
			myText.append("-"+Integer.toString(margin)+
					"-"+dm.widthPixels+"|");
			RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			lp.leftMargin=margin * i;
			myRelative.getChildAt(i).setLayoutParams(lp);
		}
	}
}
